<?php

namespace App\Admin\Controllers;

use App\Models\Productline;
use App\Models\StopReason;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\MessageBag;

class StopReasonController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $productlines = Productline::get(['id', 'name']);
        $productlineSelectOptions = [];
        $currentProductlineId = request('productlineId', $productlines->first()->id);

        $tree = StopReason::tree(function ($tree) {
            $tree->branch(function ($branch) {
                $row = sprintf('%s - %s', $branch['id'], $branch['name']);
                if ($branch['parentId'] == 0) {
                    $productline = Productline::findOrFail($branch['productlineId']);
                    $row .= sprintf(' (生产线：%s,  类型：%s)', $productline->name, StopReason::$typeTexts[$branch['type']]);
                }
                return $row;
            });
        });
        $tree->disableSave();
        $tree->disableRefresh();
        $tree->disableCreate();
        $tree->nestable([
            'dragClass' => 'dontDoThat',
            'handleClass' => 'dontDoThat',
        ]);
        $tree->query(function ($query) use ($currentProductlineId) {
            return $query->where('productlineId', $currentProductlineId);
        });
        $tree->setView([
            'tree'   => 'admin::tree',
            'branch' => 'stop-reason',
        ]);


        $productlines->each(function ($item) use (&$productlineSelectOptions, $currentProductlineId) {
            $selected = $currentProductlineId == $item->id ? ' selected' : '';
            $productlineSelectOptions[] = sprintf('<option value="%s"%s>%s</option>', $item->id, $selected, $item->name);
        });
        $productlineSelectHtml = implode('', $productlineSelectOptions);
        $createBtnUrl = route('admin.stop-reason.create', ['productlineId' => $currentProductlineId]);

        $productlineFilter = <<<EOT
<form class="form-inline" method="get">
  <div class="form-group">
    <label for="exampleInputName2">切换生产线：</label>
    <select class="form-control" name="productlineId">
      $productlineSelectHtml
    </select>
  </div>
  <button type="submit" class="btn btn-default">切换</button>
  <a class="btn btn-success btn-sm" href="$createBtnUrl">
    <i class="fa fa-save"></i>
    <span class="hidden-xs">&nbsp;新增</span>
   </a>
</form>
EOT;

        $tree->tools(function ($tools) use ($productlineFilter) {
            $tools->add($productlineFilter);
        });

        return $content
            ->header('Index')
            ->description('description')
            ->body($tree);
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        $productline = $this->getProductline();
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form($productline)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        $productline = $this->getProductline();
        return $content
            ->header($productline->name)
            ->description('停机原因')
            ->body($this->form($productline));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StopReason);

        $grid->id('Id');
        $grid->name('Name');
        $grid->description('Description');
        $grid->productlineId('ProductLineId');
        $grid->parentId('ParentId');
        $grid->type('Type');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(StopReason::findOrFail($id));

        $show->id('Id');
        $show->name('Name');
        $show->description('Description');
        $show->productlineId('ProductLineId');
        $show->parentId('ParentId');
        $show->type('Type');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($productline = null)
    {
        if (!$productline) {
            $productline = new Productline();
        }
        $form = new Form(new StopReason);
        $form->hidden('productlineId', '生产线')->value($productline->id);
        $form->select('parentId', '上级')->options(
            StopReason::selectOptions(function ($query) use ($productline) {
                return $query->where('productlineId', $productline->id);
            })
        );
        $form->text('name', '名称')->rules(['required']);
        $form->textarea('description', '描述');
        $form->radio('type', '类型')->options(StopReason::$typeTexts)->help('只有一级时有效');

        $form->saving(function ($form) {
            if ($form->parentId) {
                $parent = StopReason::findOrFail($form->parentId);
                if ($parent->productlineId != $form->productlineId) {
                    $productline = Productline::findOrFail($form->productlineId);
                    $error = new MessageBag([
                        'title'   => '选择错误',
                        'message' => "父级所属生产线：{$parent->name}【{$parent->id}】 与所选生产线：{$productline->name}【{$productline->id}】不一致",
                    ]);
                    return back()->with(compact('error'));
                }
                $form->type = $parent->type;
            } elseif (!$form->type) {
                $error = new MessageBag([
                    'title'   => '数据不完整',
                    'message' => '一级原因请选择类型',
                ]);
                return back()->with(compact('error'));
            }

        });

        $form->saved(function ($form) use ($productline) {
            return redirect(route('admin.stop-reason.index', ['productlineId' => $productline->id]));
        });

        $form->tools(function ($tools) use ($productline) {
            $tools->disableList();
            $tools->append(formListUrl(route('admin.stop-reason.index', ['productlineId' => $productline->id])));
        });

        return $form;
    }

}
